package cloudspace.ui.applet;

import java.util.ArrayList;
import java.util.List;


public class CloudToApplet
{
    boolean isError = false;

    List<String> params = new ArrayList<String>();


    public CloudToApplet( Throwable throwable )
    {
        buildParams( throwable.getClass().getName(), throwable.getMessage() );
        isError = true;
    }


    public CloudToApplet( Object... params )
    {
        if ( params != null )
            buildParams( params );
        isError = false;
    }


    public boolean isError()
    {
        return isError;
    }


    private void buildParams( Object... toAdd )
    {
        if ( toAdd != null )
            for ( Object param : toAdd )
            {
                if ( param != null )
                    params.add( param.toString() );
            }
    }


    public String getRequestScript( String reqId )
    {
        String requestScript = "";
        reqId = "\"" + reqId + "\"";
        String callParams = "var params = new Array(" + params.size() + ");";
        if ( params.size() != 0 )
        {
            for ( int i = 0; i < params.size(); i++ )
            {
                callParams += "params[" + i + "] = '" + params.get( i ) + "';";
            }
        }
        // if ( params.length() == 0 )
        // callParams += reqId;
        // else
        // callParams += reqId + ", " + params;
        if ( isError )
            requestScript += callParams + "getApplet().notifyError(" + reqId
                + ", params);";
        else
            requestScript += callParams + "getApplet().notifyResult(" + reqId
                + ", params);";
        requestScript = requestScript.replace( "\n", "\\n" );
        return requestScript;
    }
}
